package com.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.entity.pojo.FoodFavorite;
import com.food.mapper.FoodFavoriteMapper;
import com.food.service.FoodFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.entity.dto.FoodFavoriteDto;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class FoodFavoriteServiceImpl extends ServiceImpl<FoodFavoriteMapper, FoodFavorite> implements FoodFavoriteService {

    @Override
    public void addFavorite(FoodFavoriteDto dto) {
        // 判断是否已收藏
        QueryWrapper<FoodFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", dto.getUserId())
                .eq("food_id", dto.getFoodId());

        if (count(wrapper) > 0) {
            throw new RuntimeException("该用户已收藏此美食");
        }

        FoodFavorite favorite = new FoodFavorite();
        favorite.setUserId(dto.getUserId());
        favorite.setFoodId(dto.getFoodId());
        favorite.setCreatedAt(new Date());
        save(favorite);
    }

    @Override
    public List<FoodFavorite> getFavoritesByUserId(Integer userId) {
        return query().eq("user_id", userId).list();
    }

    @Override
    public void deleteFavorite(Integer userId, Integer foodId) {
        QueryWrapper<FoodFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("food_id", foodId);
        remove(wrapper);
    }
}
